package com.wis.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

//import com.umeng.analytics.MobclickAgent;
import com.wis.R;
import com.wis.application.WisApplication;
import com.wis.face.WisUtil;
import com.wis.util.MyPreferences;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener {

    private WisApplication application;
    private LinearLayout compareLayout, detectLayout, manageLayout;
    private EditText fazhiEt;
    private Button setBtn;
    // 手机按钮监听
    private long preTime;



    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    private static final int PERMISSON_REQUESTCODE = 0;
    private static final int SETTING_REQUESTCODE = 1;

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;

//    private void test()
//    {
//        Bitmap bmp = BitmapFactory.decodeFile("/sdcard/wis/images/1.jpg");
//        byte[] rgbData = WisUtil.getRGBByBitmap(bmp);
//        //detect face return face rect(x,y,width,height) in picture
//        long startTime = System.nanoTime();
//        int[] ret = application.getWisMobile().detectFace(rgbData, bmp.getWidth(),
//                bmp.getHeight(), bmp.getWidth() * 3);
//        long consumingTime = System.nanoTime() - startTime;
//        Log.i("wisMobile", "detect time  " + consumingTime/1000);
//        int faceCount = ret[0];
//        if (faceCount>0)
//        {
//            Log.i("wisMobile", "detectFace size=" + ret[0] + ",rect(x,y,width,height) = " + ret[1] + "," + ret[2] + "," + ret[3] + "," + ret[4]);
//        }
//
//    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        checkPermissions(needPermissions);

        Log.i("MainActivity", "onCreate");

        //加载模型
        application = (WisApplication) getApplication();
        application.loadWisMobile();
        TextView tv = (TextView) findViewById(R.id.txt_ser);
        String ser=application.getSerialNo();
        Log.i("MainActivity WisMobile", ser);
        tv.setText("license code="+ser);

        TextView txt_info = (TextView) findViewById(R.id.txt_qq);
//        for (int i = 0; i < 10000000; i++){
//            Log.d("wisMobile","------------->"+i);
//            test();
//        }

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                //加载模型
//                application = (WisApplication) getApplication();
//                application.loadWisMobile();
//            }
//        }).start();
    }
    /**
     * @param permissions
     * @since 2.5.0
     */
    private void checkPermissions(String... permissions) {
        List<String> needRequestPermissonList = findDeniedPermissions(permissions);
        if (null != needRequestPermissonList
                && needRequestPermissonList.size() > 0) {
            ActivityCompat.requestPermissions(this,
                    needRequestPermissonList.toArray(
                            new String[needRequestPermissonList.size()]),
                    PERMISSON_REQUESTCODE);
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(this,
                    perm) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    this, perm)) {
                needRequestPermissonList.add(perm);
            }
        }
        return needRequestPermissonList;
    }


    private void initView() {
        detectLayout = (LinearLayout) findViewById(R.id.detect_layout);
        detectLayout.setOnClickListener(this);
        compareLayout = (LinearLayout) findViewById(R.id.compare_layout);
        compareLayout.setOnClickListener(this);
        manageLayout = (LinearLayout) findViewById(R.id.manage_layout);
        manageLayout.setOnClickListener(this);
        fazhiEt= (EditText) findViewById(R.id.et_threshold);
        int fazhi = MyPreferences.getThreshold(this);
        if(fazhi>0) fazhiEt.setText(fazhi+"");
        setBtn= (Button) findViewById(R.id.btn_set);
        setBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(fazhiEt.getText().toString().length()>0){
                    int fazhi = Integer.valueOf(fazhiEt.getText().toString());
                    if(fazhi<=0){
                        Toast.makeText(MainActivity.this,"阀值为大于0小于100的整数",Toast.LENGTH_SHORT).show();
                        fazhiEt.setText(null);
                    }else {
                        if(MyPreferences.setThreshold(MainActivity.this,fazhi)){
                            Toast.makeText(MainActivity.this,"设置成功",Toast.LENGTH_SHORT).show();
                        }
                    }

                }

            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.detect_layout:

                intent = new Intent(MainActivity.this, DetectActivity.class);
                break;
            case R.id.compare_layout:
                intent = new Intent(MainActivity.this, CompareActivity.class);
                break;
            case R.id.manage_layout:
                intent = new Intent(MainActivity.this, ManageActivity.class);
                break;
            default:
                break;
        }
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 截获后退键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTime = new Date().getTime();
            // 如果时间间隔大于2秒, 不处理
            if ((currentTime - preTime) > 2 * 1000) {
                // 显示消息
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                // 更新时间
                preTime = currentTime;
                // 截获事件,不再处理
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isNeedCheck) {
            checkPermissions(needPermissions);
        }
//        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);
    }


    /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(R.string.notifyMsg);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, SETTING_REQUESTCODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SETTING_REQUESTCODE) {
            checkPermissions(needPermissions);
        }
    }
}
